package com.team2.shoppingService;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.team2.shared.ServerStore;

public class StoreRequest {
	protected double latitude=49.2817450;
	protected double longitude=-123.1206750;
	protected int radius = 10000; // in the unit of meters
	protected String storeName;
	protected String price="N/A";
	
	//API specific information
	protected String apiKey ="AIzaSyCVP6qxzIx7TAQDJJ-5zNootEcrL3fOkQE";
	protected String baseUrl = "https://maps.googleapis.com/maps/api/place/";
	protected boolean isTextSearch = true;
	
	public StoreRequest(String storeName){
		this.storeName=storeName;
	}
	public StoreRequest(String storeName, String price){
		this.storeName=storeName;
		this.price = price;
	}
	public ArrayList<ServerStore> execute(){
		
		String json = Util.getRawHttpResponse(this.toUrlString());
		
		return parseJson(json);
		
	}
	protected ArrayList<ServerStore> parseJson(String json){
		ArrayList<ServerStore> stores = new ArrayList<ServerStore> ();
		try {
			JSONObject root = new JSONObject(json);
			JSONArray list = root.getJSONArray("results");
			for (int i=0; i<list.length();i++){
				ServerStore store = new ServerStore();
				JSONObject object = list.getJSONObject(i);
				String address = object.getString("formatted_address");
				store.setName(object.getString("name"));
				store.setLatitude(object.getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
				store.setLongitude(object.getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
				store.setBrand(storeName);
				store.setPrice(price);
				store.setAddress(address);
				stores.add(store);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return stores;
	}
	protected String toUrlString(){
		String url= baseUrl;
		if(this.isTextSearch){
			url += "textsearch/json?query="+Util.encodeUrl(storeName);
		}else{
			url += "nearbysearch/json?name="+Util.encodeUrl(storeName);
		}
		url += "&location="+Double.toString(latitude)+","+Double.toString(longitude);
		url += "&radius="+Integer.toString(radius);
		url += "&sensor=false";
		url += "&rankby=distance";
		url += "&key="+apiKey;
		return url;
	}
	public double getLatitude() {
		return latitude;
	}
	public void setLatitude(double latitude) {
		this.latitude = latitude;
	}
	public double getLongitude() {
		return longitude;
	}
	public void setLongitude(double longitude) {
		this.longitude = longitude;
	}
	public int getRadius() {
		return radius;
	}
	public void setRadius(int radius) {
		this.radius = radius;
	}
	
	
}
